package airportCoordination;

import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;

public class AirportPing implements Runnable{

	private Statement sql;
	
	private String SQL_CONNECTION = "jdbc:mysql:///snevTracker";
	private String SQL_USER = "snev";
	private String SQL_PASS = "snevpw";

	private final String AIRPORTS_DIMPORT = "SELECT ip, dimPort FROM Airports";
	private final int PING_LAPSE = 3;
	private SharedBoolean active;

	public AirportPing(String sql_connection, String sql_user, String sql_pass, SharedBoolean a)
	{
		SQL_CONNECTION = sql_connection;
		SQL_USER = sql_user;
		SQL_PASS = sql_pass;
		try{
			sql = DriverManager.getConnection(SQL_CONNECTION, SQL_USER, SQL_PASS).createStatement();
		}catch(Exception e){ System.out.print("FATAL ERROR. Error conecting database: " + e.getMessage() + "\n"); System.exit(666); }
		active = a;
	}
	
	public void run()
	{
		while (true)
		{
			try{
				Thread.sleep(PING_LAPSE*60*1000);
			}catch(Exception e){ System.out.print("FATAL ERROR. Error trying to sleep AirportPing thread: " + e.getMessage() + "\n"); System.exit(666); }
			
			if (!active.value())
				continue;
			
			ResultSet airports = null;
			try{
				airports = sql.executeQuery(AIRPORTS_DIMPORT);
			}catch(Exception e){ System.out.print("Error getting airports: " + e.getMessage() + "\n"); continue; }
			
			try{
				boolean valid = airports.first();
				while (valid)
				{
					Sender.ping(airports.getString("ip"), airports.getInt("dimPort"));
					valid = airports.next();
				}
			}catch(Exception e){ System.out.print("Error sending pings: " + e.getMessage() + "\n"); continue; }
		}
	}
}
